import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * WebPage class that is an object containing a
 * web pages URL and its content.
 * 
 * @version February 1, 2012
 * @author Jay Fernandez
 */
public class WebPage {
	/** URL of the web page */
	private URL url;
	
	/** Source code of the web page */
	private String content;
	
	/**
	 * Constructor that initializes with a given address
	 * and retrieves the web pages source code from it.
	 * 
	 * @param address The URL address.
	 */
	public WebPage(String address) {
		final URL url;
		try {
			url = new URL(address);
			this.url = url;
			StringWriter sw = new StringWriter();
			BufferedInputStream in = new BufferedInputStream(url.openStream());
			for (int c = in.read(); c != -1; c = in.read()) {
				sw.write(c);
			}
			content = sw.toString();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * @return the URL of the web page.
	 */
	public URL getURL() {
		return url;
	}
	
	/**
	 * @return the content of the web page.
	 */
	public String getContent() {
		return content;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean equals(Object o) {
		boolean result = false;
		if (this == o) {
			result = true;
		} else if (o != null && o.getClass() == getClass()) {
			final WebPage other_page = (WebPage) o;
			result = other_page.getURL().toString().equals(url.toString());
		}
		return result;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public int hashCode() {
		return toString().hashCode();
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public String toString() {
		return url.toString();
	}
}
